/**
 * 项目导出模态框组件
 */

'use client';

import React, { useState, useEffect } from 'react';
import {
  Modal,
  Button,
  Space,
  Radio,
  Card,
  Descriptions,
  Spin,
  Alert,
  Typography,
  Divider,
} from 'antd';
import {
  DownloadOutlined,
  FileExcelOutlined,
  FileTextOutlined,
  BarChartOutlined,
} from '@ant-design/icons';
import { ExportUtils } from '../utils/exportUtils';
import type { Project } from '../types/workItem';

const { Text, Title } = Typography;

interface ProjectExportModalProps {
  visible: boolean;
  onCancel: () => void;
  projects: Project[];
  loading: boolean;
  searchFilters?: {
    name?: string;
    type?: string;
  };
}

export default function ProjectExportModal({
  visible,
  onCancel,
  projects,
  loading,
  searchFilters = {},
}: ProjectExportModalProps) {
  const [exportFormat, setExportFormat] = useState<'csv' | 'excel' | 'json'>('excel');
  const [exporting, setExporting] = useState(false);
  const [statistics, setStatistics] = useState<any>(null);

  // 当项目数据变化时，重新计算统计信息
  useEffect(() => {
    if (projects.length > 0) {
      const stats = ExportUtils.generateProjectStatistics(projects);
      setStatistics(stats);
    }
  }, [projects]);

  // 处理导出
  const handleExport = async () => {
    if (projects.length === 0) {
      return;
    }

    try {
      setExporting(true);
      
      // 转换为报表格式
      const reportData = ExportUtils.convertProjectsToReportData(projects);
      
      // 根据格式导出
      const hasFilters = searchFilters.name || searchFilters.type;
      const filename = hasFilters ? `项目报表_筛选结果` : `全部项目报表`;
      
      switch (exportFormat) {
        case 'csv':
          ExportUtils.exportToCSV(reportData, filename);
          break;
        case 'excel':
          ExportUtils.exportToExcel(reportData, filename);
          break;
        case 'json':
          ExportUtils.exportToJSON(reportData, filename);
          break;
      }
      
      // 关闭模态框
      onCancel();
      
    } catch (error) {
      console.error('导出失败:', error);
    } finally {
      setExporting(false);
    }
  };

  // 格式选项
  const formatOptions = [
    {
      label: (
        <Space>
          <FileExcelOutlined style={{ color: '#1890ff' }} />
          <span>Excel格式 (.csv)</span>
          <Text type="secondary">推荐，可用Excel打开</Text>
        </Space>
      ),
      value: 'excel',
    },
    {
      label: (
        <Space>
          <FileTextOutlined style={{ color: '#52c41a' }} />
          <span>CSV格式 (.csv)</span>
          <Text type="secondary">纯文本，兼容性好</Text>
        </Space>
      ),
      value: 'csv',
    },
    {
      label: (
        <Space>
          <BarChartOutlined style={{ color: '#fa8c16' }} />
          <span>JSON格式 (.json)</span>
          <Text type="secondary">结构化数据，便于程序处理</Text>
        </Space>
      ),
      value: 'json',
    },
  ];

  return (
    <Modal
      title={
        <Space>
          <DownloadOutlined />
          <span>导出项目报表</span>
        </Space>
      }
      open={visible}
      onCancel={onCancel}
      width={700}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button
          key="export"
          type="primary"
          icon={<DownloadOutlined />}
          onClick={handleExport}
          loading={exporting}
          disabled={loading || projects.length === 0}
        >
          导出 ({projects.length} 个项目)
        </Button>,
      ]}
    >
      <div className="space-y-4">
        {/* 导出说明 */}
        <Alert
          message="导出说明"
          description={
            <div>
              <p>• 将导出全部项目的完整信息，包括项目名称、类型、状态、负责人等详细数据</p>
              <p>• 如果设置了搜索条件，将只导出符合条件的项目</p>
              <p>• 导出的文件将自动添加时间戳，避免文件名冲突</p>
            </div>
          }
          type="info"
          showIcon
        />

        {/* 当前筛选条件 */}
        {(searchFilters.name || searchFilters.type) && (
          <Card size="small" title="当前筛选条件">
            <Space direction="vertical" style={{ width: '100%' }}>
              {searchFilters.name && (
                <Text>项目名称: <Text code>{searchFilters.name}</Text></Text>
              )}
              {searchFilters.type && (
                <Text>项目类型: <Text code>{searchFilters.type}</Text></Text>
              )}
            </Space>
          </Card>
        )}

        {/* 数据统计 */}
        {loading ? (
          <Card size="small" title="数据统计">
            <div className="text-center py-4">
              <Spin />
              <div className="mt-2">正在获取项目数据...</div>
            </div>
          </Card>
        ) : statistics ? (
          <Card size="small" title="数据统计">
            <Descriptions column={2} size="small">
              <Descriptions.Item label="总项目数" span={2}>
                <Text strong style={{ fontSize: '16px', color: '#1890ff' }}>
                  {statistics.总项目数}
                </Text>
              </Descriptions.Item>
              
              <Descriptions.Item label="项目类型">
                <Space direction="vertical" size="small">
                  {Object.entries(statistics.项目类型统计).map(([type, count]) => (
                    <Text key={type}>{type}: {count as number}</Text>
                  ))}
                </Space>
              </Descriptions.Item>
              
              <Descriptions.Item label="项目状态">
                <Space direction="vertical" size="small">
                  {Object.entries(statistics.状态统计).map(([state, count]) => (
                    <Text key={state}>{state}: {count as number}</Text>
                  ))}
                </Space>
              </Descriptions.Item>
              
              <Descriptions.Item label="可见性">
                <Space direction="vertical" size="small">
                  {Object.entries(statistics.可见性统计).map(([visibility, count]) => (
                    <Text key={visibility}>{visibility}: {count as number}</Text>
                  ))}
                </Space>
              </Descriptions.Item>
              
              <Descriptions.Item label="归档状态">
                <Space direction="vertical" size="small">
                  {Object.entries(statistics.归档统计).map(([archived, count]) => (
                    <Text key={archived}>{archived}: {count as number}</Text>
                  ))}
                </Space>
              </Descriptions.Item>
            </Descriptions>
          </Card>
        ) : null}

        <Divider />

        {/* 导出格式选择 */}
        <div>
          <Title level={5}>选择导出格式</Title>
          <Radio.Group
            value={exportFormat}
            onChange={(e) => setExportFormat(e.target.value)}
            className="w-full"
          >
            <Space direction="vertical" className="w-full">
              {formatOptions.map((option) => (
                <Radio key={option.value} value={option.value} className="w-full">
                  <div className="py-2">{option.label}</div>
                </Radio>
              ))}
            </Space>
          </Radio.Group>
        </div>
      </div>
    </Modal>
  );
}